package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService{

 @Value("${file.localDir}")
 private  String localDir;
 @Value("${file.urlPath}")   //spel表达式，从yml文件获取值
 private String urlPath;



 @Override
 public ImageVO upload(MultipartFile file) {
  //文件类型校验
  String fileName=file.getOriginalFilename();
  fileName=fileName.toLowerCase();//放止Windows系统大小写不分
  if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
   return null;
  }

  //文件详细校验
  try {
   BufferedImage bufferedImage=ImageIO.read(file.getInputStream());
   int width=bufferedImage.getWidth();
   int height=bufferedImage.getHeight();
   if(width==0||height==0){
    return null;
   }
  } catch (IOException e) {
   e.printStackTrace();
   return null;
  }

  //获取时间目录，代码的结果为时间目录，例如：/2019/04/22,用时间作为目录
  String dateDir=new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
  //
  String fileDir=localDir+dateDir;



  File dirFile=new File(fileDir);
  if(!dirFile.exists()){
   dirFile.mkdirs();
  }

  //uuid不会重复
  String uuid= UUID.randomUUID().toString().replace("-","");
  int index=fileName.lastIndexOf('.');
  String fileType=fileName.substring(index);
  String realFileName=uuid+fileType;

  String realFilePath=fileDir+realFileName;

  //如果上传图片太大，就会失败，最大不能超过1048576 bytes
  try {
   file.transferTo(new File(realFilePath));


   ImageVO imageVO=new ImageVO();
   imageVO.setVirtualPath(realFilePath);
   imageVO.setFileName(realFileName);
   String url=urlPath+dateDir+realFileName;
   imageVO.setUrlPath(url);

   return imageVO;
  }catch (IOException e){
   e.printStackTrace();
   return null;
  }

 }


}

















